<template>
  <div class="table-page-search-wrapper" style="margin-top: -20px">
    <a-form layout="horizontal" @keyup.enter.native="searchQuery">
      <!-- 基础信息区域 -->
      <div class="form-section">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              label="关键字搜索:"
              prop="keywords"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-input
                placeholder="资产码、设备名称、品牌、型号、序列号、号码牌"
                v-model="queryParam.keywords"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="设备短码:"
              prop="deviceShortCode"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-input
                v-model="queryParam.deviceShortCode"
                placeholder="请输入设备短码(例如:1123321,12133)"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              label="专业分类"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-tree-select
                v-model:value="queryParam.professionalClassificationId"
                :tree-data="professionalClassificationIdTree"
                tree-checkable
                :treeCheckStrictly="true"
                allow-clear
                placeholder="请选择专业分类"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="使用科室"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-tree-select
                v-model="queryParam.usingDepartmentId"
                tree-checkable
                :treeCheckStrictly="true"
                allow-clear
                :tree-data="departmentTree"
                placeholder="请选择使用科室"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 底部查询按钮 -->
      <div class="form-footer">
        <a-button
          type="primary"
          @click="$refs.table.refresh(true)"
          style="width: 65px; height: 30px; padding-left: 17px"
          >查询</a-button
        >
        <a-button
          @click="
            () => {
              this.$objToReset(queryParam), $refs.table.refresh(true)
            }
          "
          style="
            margin-left: 8px;
            width: 65px;
            height: 30px;
            padding-left: 17px;
          "
          >重置</a-button
        >
      </div>
    </a-form>
    <div class="table-operator">
      <a @click="closeCheckAll" v-if="isCheckAll">取消选择全部</a>
      <a @click="checkAll" v-else>选择全部</a>
    </div>
    <!--  -->
    <s-table
      v-if="isCheckAll"
      ref="table"
      rowKey="id"
      size="middle"
      :columns="columns"
      :alert="options.alert"
      :scroll="{ x: 500 }"
      :data="loadData"
    >
      <template slot="usingDepartmentId" slot-scope="text, record">
        {{ getUsingDepartmentId(text) }}
      </template>
    </s-table>
    <s-table
      v-else
      ref="table"
      rowKey="id"
      size="middle"
      :columns="columns"
      :alert="options.alert"
      :scroll="{ x: 500 }"
      :row-selection="options.rowSelection"
      :data="loadData"
    >
      <template slot="usingDepartmentId" slot-scope="text, record">
        {{ getUsingDepartmentId(text) }}
      </template>
    </s-table>
    <div style="display: flex; margin-top: 10%; justify-content: flex-end">
      <a-button style="margin-right: 0.8rem" @click="handlebClose"
        >取消</a-button
      >

      <a-button @click="handleSubmit" type="primary">确认</a-button>

      <!-- <div style="margin-bottom: 5%"></div> -->
    </div>
  </div>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { deleteAction, postAction, getAction } from '@/api/manage'
import { mixin } from '@/utils/mixin'

import { getDepartTree, getCompanyList } from '@/api/api'

export default {
  name: 'DevArchiveEquipmentList',
  mixins: [mixin],
  components: {
    STable,
    Ellipsis,
  },
  data() {
    return {
      isCheckAll: false,
      filterGroupVisible: false,
      createByList: [],
      activeKey: '-1',
      visible: false,
      // 查询条件
      queryParam: {
        deviceShortCode: undefined,
        commonName: undefined,
        cfda: undefined,
        activeState: undefined,
        assetStatus: undefined,
        repairState: undefined,
        assetCode: undefined,
        fixedAssets: undefined,
        period: undefined,
        deviceType: undefined,
        assetCode: undefined,
        currentLocation: undefined,
        departmentId: undefined,
        usingDepartmentId: undefined,
        supplierName: undefined,
        importedDomestic: undefined,
        differentCountrie: undefined,
        manufacturerName: undefined,
        assetValueMin: undefined,
        assetValueMax: undefined,
        purchaseDate: undefined,
        expiringDate: undefined,
        acceptanceDate: undefined,
        entryDate: undefined,
        inputMethod: undefined,
        enterSource: undefined,
        administrativeDept: undefined,
        deviceClassificationId: undefined,
        mandatoryInspectionCatalogId: undefined,
        politicalProcurementCatalogueId: undefined,
        commonMilitaryNameId: undefined,
        fixedClassificationId: undefined,
        fixedAssetClassificationCodeId: undefined,
      },
      isDisabled: {
        commonName: false,
        cfda: false,
        activeState: false,
        assetStatus: false,
        repairState: false,
        assetCode: false,
        fixedAssets: false,
        period: false,
        deviceType: false,
        assetCode: false,
        currentLocation: false,
        departmentId: false,
        usingDepartmentId: false,
        supplierName: false,
        importedDomestic: false,
        differentCountrie: false,
        manufacturerName: false,
        assetValueMin: false,
        assetValueMax: false,
        purchaseDate: false,
        expiringDate: false,
        acceptanceDate: false,
        entryDate: false,
        inputMethod: false,
        enterSource: false,
        administrativeDept: false,
        deviceClassificationId: false,
        mandatoryInspectionCatalogId: false,
        politicalProcurementCatalogueId: false,
        commonMilitaryNameId: false,
        fixedClassificationId: false,
        fixedAssetClassificationCodeId: false,
      },
      // 表头
      // 如果需要字典，那么需要在columns列中加入 customRender: (text) => this.$sysDictFilter(text, 'xxxx')xxxx 为dataIndex
      columns: [
        {
          title: '设备短码',
          dataIndex: 'deviceShortCode',

          scopedSlots: { customRender: 'deviceShortCode' },
        },

        {
          title: '设备名称',
          dataIndex: 'deviceName',
        },

        {
          title: '品牌',
          dataIndex: 'bind',
        },
        {
          title: '型号',
          dataIndex: 'model',
        },
        {
          title: '使用科室',
          dataIndex: 'usingDepartmentId',
          customRender: (text) => this.getUsingDepartmentId(text),
          // scopedSlots: { customRender: 'usingDepartmentId' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return postAction(
          this.url.list,
          Object.assign(parameter, this.queryParam)
        ).then((res) => {
          return res.result
        })
      },
      deviceTypeTree: [],
      professionalClassificationIdTree: [],
      deviceClassificationTree: [],
      mandatoryInspectionCatalogTree: [],
      politicalProcurementCatalogueTree: [],
      commonMilitaryNameTree: [],
      fixedClassificationTree: [],
      fixedAssetClassificationCodeTree: [],
      campusBuildingFloorRoomTree: [],
      departmentTree: [],
      commonNameList: [],
      selectedRowKeys: [],
      options: {
        alert: {
          clear: () => {
            this.selectedRowKeys = []
          },
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
          type: 'checkbox',
        },
      },
      groupList: [],
      url: {
        list: '/system/devArchiveEquipment/list',
        delete: '/system/devArchiveEquipment/delete',
        getListFilterGroupStatistic:
          '/system/devArchiveEquipment/getListFilterGroupStatistic',
        getDeviceTypeTree: '/system/ktree/tree',
        getprofessionalClassificationIdTree:
          '/system/devProfessionalClassification/tree',
        getClassificationTree: '/system/devArchiveDeviceClassification/tree',
        getMandatoryInspectionCatalogTree:
          '/system/devArchiveMandatoryInspectionCatalog/tree',
        getPoliticalProcurementCatalogueTree:
          '/system/devArchivePoliticalProcurementCatalogue/tree',
        getCommonMilitaryNameTree: '/system/devArchiveCommonMilitaryName/tree',
        getFixedClassificationTree:
          '/system/devArchiveFixedClassification/tree',
        getFixedAssetClassificationCodeTree:
          '/system/devArchiveFixedAssetClassificationCode/tree',
        getCampusBuildingFloorRoomTree:
          '/system/devCampusBuildingFloorRoom/listTree',
        getDevArchiveCommonNameList: '/system/devArchiveCommonName/getList',
      },
      toggleSearchStatus: false,
      checkEquipmentList: [],
    }
  },
  computed: {},
  created() {
    //使用科室
    this.getDepartment()
  },
  methods: {
    handlebClose() {
      this.$emit('close', '')
      this.checkEquipmentList = []
    },
    handleSubmit() {
      if (
        this.checkEquipmentList.length <= 0 &&
        this.selectedRowKeys.length <= 0
      ) {
        this.$message.error('请选择设备')
        return
      }

      if (this.selectedRowKeys) {
        this.selectedRowKeys.forEach((id) => {
          console.log('this.id>>', id)
          this.checkEquipmentList.push({ id: id })
        })
      }

      this.$emit('ok', this.checkEquipmentList)
      this.handlebClose()
    },
    closeCheckAll() {
      this.isCheckAll = false
      this.checkEquipmentList = []
      this.$message.success('取消选择全部成功')
    },
    checkAll() {
      this.isCheckAll = true
      var parameter = { pageNo: 1, pageSize: 200000000 }
      postAction(this.url.list, Object.assign(parameter, this.queryParam)).then(
        (res) => {
          console.log('XXX', res.result.data.records)
          this.checkEquipmentList = res.result.data.records
        }
      )
      this.$message.success('选择全部成功')
    },
    getUsingDepartmentId(text) {
      if (text) {
        var names = ''
        var usingDepartmentList = text.split(',')
        usingDepartmentList.forEach((usingDepartmentId) => {
          var value = this.getFindNodeByKey(
            this.departmentTree,
            usingDepartmentId
          )
          names = names + value.title + ','
        })
        if (names) {
          names = names.substring(0, names.length - 1)
        }
        console.log('value>>', names)
        return names
      }
    },
    getFindNodeByKey(tree, key) {
      console.log('XXXKey>', key)
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].value === key) {
          return tree[i] // 找到匹配项，返回该节点
        } else if (tree[i].children) {
          // 递归搜索子节点
          const found = this.getFindNodeByKey(tree[i].children, key)
          if (found) return found // 如果在子节点中找到，返回该节点
        }
      }
      return null // 未找到匹配项
    },
    //使用科室
    getDepartment() {
      getDepartTree().then((res) => {
        this.departmentTree = res.result.data
      })
    },

    //专业分类
    getprofessionalClassificationId() {
      getAction(this.url.getprofessionalClassificationIdTree, {}).then(
        (res) => {
          this.professionalClassificationIdTree = res.result.data
        }
      )
    },

    // 用户编辑
    handleEdit(record) {
      record.type = '0'
      this.$refs.modalEdit.edit(record)
    },
    searchQuery() {
      this.$refs.table.refresh(true)
    },
    // 保存刷新
    modalEditOk() {
      this.$refs.table.refresh()
    },
    // 查看
    handelView(record) {
      this.$refs.modalView.show(record)
    },
    //开启选择
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
  },
  watch: {},
}
</script>
<style scoped>
body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
    'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f0f2f5;
  color: #333;
  margin: 0;
  padding: 20px;
}
.container {
  max-width: 1600px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 20px 24px;
}
.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}
.system-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d39c4;
  letter-spacing: 1px;
}
.form-section {
  padding: 0% 1% 0% 0%;
  margin-left: -2.5%;
  /* background: #fafafa; */
  /* padding: 16px 20px;
  border-radius: 4px;
  margin-bottom: 24px; */
  /* border: 1px solid #f0f0f0; */
}
.section-title {
  font-weight: 600;
  margin-bottom: 16px;
  color: #2f54eb;
  position: relative;
  padding-left: 12px;
  font-size: 16px;
}
.section-title:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 18px;
  background: #2f54eb;
  border-radius: 3px;
}
.date-range-container {
  display: flex;
  gap: 8px;
}
.date-range-container .ant-picker {
  flex: 1;
}
.form-footer {
  display: flex;
  justify-content: flex-end;

  gap: 16px;
}
.ant-row {
  /* margin-bottom: 14px; */
}
.ant-input,
.ant-select-selector,
.ant-picker {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}
.ant-select-selector {
  padding: 1px 11px;
}
.ant-col .ant-form-item-label {
  text-align: right;
  padding-right: 8px;
}
.ant-btn {
  border-radius: 4px;
  height: 34px;
  padding: 0 20px;
  font-weight: 500;
}
.ant-btn-primary {
  background: #1890ff;
  border-color: #1890ff;
}
.ant-btn-default {
  border-color: #d9d9d9;
  color: #333;
}
.value-range {
  display: flex;
  align-items: center;
  gap: 8px;
}
.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-action {
  display: flex;
  gap: 12px;
}
.search-btn {
  background: #1890ff;
  color: white;
}
.custom-label {
  font-size: 14px;
  color: #595959;
  white-space: nowrap;
}
.input-group {
  display: flex;
  gap: 10px;
}
/* .form-footer .ant-btn:nth-child(2) {
  background: #096dd9;
  border-color: #096dd9;
} */
@media (max-width: 1400px) {
  .container {
    padding: 15px;
  }
}
.ant-card-body {
  padding: 10px !important;
}
</style>
